﻿using System.Linq;
using DreamStore.WebShop.Models;
using DreamStore.WebShop.Services;
using DreamStore.WebShop.ViewModels;
using JetBrains.Annotations;
using Orchard.ContentManagement.Drivers;

namespace DreamStore.WebShop.Drivers
{
    [UsedImplicitly]
    public class CustomerDiscountsPartDriver : ContentPartDriver<CustomerDiscountsPart>
    {
        private const string TemplateName = "Parts/CustomerDiscounts";
        protected override string Prefix
        {
            get { return "CustomerDiscounts"; }
        }

        private readonly ICustomerDiscountService _customerDiscountService;

        public CustomerDiscountsPartDriver(ICustomerDiscountService customerDiscountService)
        {
            this._customerDiscountService = customerDiscountService;
        }

        protected override DriverResult Display(CustomerDiscountsPart part, string displayType, dynamic shapeHelper)
        {
            return ContentShape("Parts_CustomerDiscounts", () => shapeHelper.Parts_CustomerDiscounts(Part: part, Discounts: part.Discounts));
        }
        
        protected override DriverResult Editor(CustomerDiscountsPart part, dynamic shapeHelper)
        {
            return ContentShape("Parts_CustomerDiscounts_Edit",
                    () => shapeHelper.EditorTemplate(
                        TemplateName: TemplateName,
                        Model: BuildEditorViewModel(part),
                        Prefix: Prefix));;
        }
        
        protected override DriverResult Editor(CustomerDiscountsPart part, Orchard.ContentManagement.IUpdateModel updater, dynamic shapeHelper)
        {
            var model = new EditCustomerDiscountsViewModel();
            updater.TryUpdateModel(model, Prefix, null, null);

            if (part.ContentItem.Id != 0) {
                _customerDiscountService.UpdateCustomerDiscountsForContentItem(
                    part.ContentItem, model.CustomerDiscountProgramEntries);
            }

            return Editor(part, shapeHelper);
        }

        private EditCustomerDiscountsViewModel BuildEditorViewModel(CustomerDiscountsPart part)
        {
            var discounts = part.Discounts.ToLookup(d => d.Id);
            return new EditCustomerDiscountsViewModel
                   {
                       CustomerDiscountProgramEntries = _customerDiscountService.GetCustomerDiscounts()
                       .Select(d => new CustomerDiscountProgramEntry
                                    {
                                        CustomerDiscountProgram = d,
                                        IsChecked = discounts.Contains(d.Id)
                                    }).ToList()
                   };
        }
    }
}